package run.siyuan.rabbitmq.demo;


import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @className: RabbitmqCustomer
 * @Description: TODO 消费者
 * @author: siyuan
 * @date: 2022/3/7 11:02 PM
 */
public class RabbitmqCustomer {

    public static final String EXCHANGE_NAME = "rabbit_demo";
    public static final String QUEUE_NAME = "queue_demo";
    public static final String ROUTING_KEY = "routingkey_demo";

    public static void main(String[] args) {
        try {
            Address[] addresses = {
                    new Address("127.0.0.1", 5672)
            };
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("guest");
            connectionFactory.setPassword("guest");
            Connection connection = connectionFactory.newConnection(addresses);
            Channel channel = connection.createChannel();
            Consumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("rabbitmq demo: " + new String(body));
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            channel.basicConsume(QUEUE_NAME,consumer);
            TimeUnit.SECONDS.sleep(5);
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}
